<?php

namespace app\api\controller;

use app\common\BaseHelper;
use app\admin\model\Productcomment as ProductcommentMdl;
use app\admin\model\Order;
use app\admin\model\Orderitem;
use app\admin\model\Member;
use app\admin\model\Integralrecord;
use app\admin\model\Image;

use think\Db;
use think\Exception;

class Productcomment extends Base
{

    /**
     * 评价列表
     */
    public function getList()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '会员ID(memberId) 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '类型(type) 不能为空');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '类型(type) 格式不正确');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        if ($param->type == 1) {
            // 待评价
            $where = [
                'a.is_comment' => 0,
                'o.member_id' => $param->memberId,
                'o.status' => 4
            ];

            $model = new Orderitem();
            $join = [
                ['__ORDER__ o', 'o.id = a.order_id'],
                ['__PRODUCT__ b', 'b.id = a.product_id'],
            ];
            $fields = 'a.id as order_item_id, a.product_id, b.name, b.img_url, b.unit, b.spec, b.describe';
            $order = 'a.create_date DESC';
            $list = $model->alias('a')->where($where)->join($join)->field($fields)->limit($start, $length)->order($order)->select();
            if (!$list) {
                return show(config('status.ERROR_STATUS'), '没有评价', '没有评价');
            }
            $total = $model->alias('a')->where($where)->join($join)->count();
        } else {
            // 已评价
            $where = [
                'a.member_id' => $param->memberId,
                'a.is_delete' => 2,
            ];

            $model = new ProductcommentMdl();
            $fields = 'a.id, a.product_id, b.name, b.img_url, b.price, b.unit, b.spec, b.describe';
            $order = 'a.create_date DESC';
            $list = $model->alias('a')->where($where)->join('__PRODUCT__ b', 'a.product_id = b.id')->field($fields)->limit($start, $length)->order($order)->select();
            if (!$list) {
                return show(config('status.ERROR_STATUS'), '没有评价', '没有评价');
            }
            foreach ($list as &$item) {
                $unitArr = get_product_unit();
                $item['unit'] = $unitArr[$item['unit']];
            }
            $total = $model->alias('a')->where($where)->join('__PRODUCT__ b', 'a.product_id = b.id')->count();
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }

    /**
     * 评价详情
     */
    public function getDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->commentId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '评价ID(commentId) 不能为空');
        }

        $where = [
            'a.id' => $param->commentId
        ];
        $model = new ProductcommentMdl();
        $fields = 'a.id, a.score, a.content, a.product_id, b.name, b.img_url, b.price, b.unit, b.spec, b.describe';
        $item = $model->alias('a')->where($where)->join('__PRODUCT__ b', 'a.product_id = b.id')->field($fields)->find();
        if (empty($item)) {
            return show(config('status.ERROR_STATUS'), '未查到相关评价', '未查到相关评价');
        }

        // 单位
        $unitArr = get_product_unit();
        $item['unit'] = $unitArr[$item['unit']];

        // 评论图片
        $imgUrls = Image::where(['related_id' => $item['id']])->field('img_url')->order('sorting ASC')->select();
        $item['img_urls'] = $imgUrls;

        // 回复
        $item['responds'] = $model->where(['responder_id' => $item['id']])->field('create_date, content')->find();

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 评价
     */
    public function evaluate()
    {
        $param = self::getHttpParam();

        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '会员ID(memberId) 不能为空');
        }
        if (empty($param->productId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '商品ID(productId) 不能为空');
        }
        if (empty($param->score)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '评分(score) 不能为空');
        }
        if (empty($param->orderItemId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '订单明细ID(orderItemId) 不能为空');
        }
        if (empty($param->content) || !trim($param->content)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '评价内容(content) 不能为空');
        }

        $memberId = $param->memberId;

        Db::startTrans();
        try {
            $model = new ProductcommentMdl();
            $data = [
                'create_date' => date('Y-m-d H:i:s'),
                'order_item_id' => $param->orderItemId,
                'product_id' => $param->productId,
                'member_id' => $param->memberId,
                'score' => $param->score,
                'content' => $param->content,
            ];
            $result = $model->insert($data);

            if ($result !== false) {
                // 图片
                $res = '';
                if(isset($param->imgUrls) && $param->imgUrls) {
                    $data['id'] = $model->where(['order_item_id' => $param->orderItemId, 'product_id' => $param->productId, 'member_id' => $param->memberId])->value('id');
                    $imgUrls = (array) $param->imgUrls;
                    foreach($imgUrls as $key => $imgUrl){
                        $res = Image::where(['img_url' => $imgUrl])->update(['related_id' => $data['id'], 'controller' => 'Productcomment', 'related_table' => 'product_comment', 'tag' => 'img_list', 'sorting' => $key]);
                    }
                }
                if($res === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), '保存图片失败', '保存图片失败');
                }

                // 更新订单明细状态，改为已评价
                $orderItemRes = Orderitem::where(['id' => $param->orderItemId])->update(['is_comment' => 1]);
                if($orderItemRes === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), '更新订单明细状态失败', '更新订单明细状态失败');
                }

                // 评价晒单送积分
                $integralRule = db('integral_rule')->find();
                $integralRes = Member::where('id', $memberId)->setInc('integral', $integralRule['comment']);
                if($integralRes === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), '评价晒单送积分失败', '评价晒单送积分失败');
                }

                // 添加积分记录
                $integralData = [
                    'create_date' => date('Y-m-d H:i:s'),
                    'order_no' => BaseHelper::getUUID(),
                    'integral_id' => '',
                    'coupon_id' => '',
                    'member_id' => $param->memberId,
                    'num' => 1,
                    'exchange_num' => $integralRule['comment'],
                    'type' => 1,
                    'source' => '评价晒单',
                ];
                $intRecordRes = Integralrecord::insert($integralData);
                if($intRecordRes === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), '添加积分记录失败', '添加积分记录失败');
                }

                Db::commit();
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
            } else {
                Db::rollback();
                return show(config('status.ERROR_STATUS'), '评价失败', '评价失败');
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), '评价失败', $e->getMessage());
        }
    }
}